
import time
from pathlib import Path
from typing import List

import pyautogui
from selenium.webdriver.remote.webdriver import WebDriver

from app.configs.constant import VideoInfo
from app.utils.utils_os import OperatingSystem, current_os_name
from app.utils.utils_selenium import (click_element, driver, input_element,
                                      save_image)


class KuaiShouUpload(object):

    def __init__(self, driver: WebDriver) -> None:
        self.driver = driver

    def login(self, url: str):
        """
            登录
        """

        self.driver.get(url)

        try:
            # 点击 登录
            click_element(
                self.driver, """ //a[@class="login"] """)
        except Exception as e:
            pass
        # 点击 二维码登录
        click_element(
            self.driver, """ //div[@class="platform-switch platform-switch-pc default svelte-irseqx"] """)

    def save_qr_code(self, save_path):
        """
            保存二维码
        """
        is_login = False
        try:
            # 点击刷新
            click_element(
                self.driver, """ //div[@class="qrcode-status qrcode-status-timeout svelte-x4dxpn"]/p """)
            import time
            time.sleep(2)
            is_login = False
        except Exception as e:
            is_login = True

        try:
            save_image(self.driver, """ //img[@class="svelte-x4dxpn"] """, save_path=save_path)
            is_login = False
        except Exception as e:
            is_login = True

        return is_login

    def pre_upload(self):
        """
            准备上传
        """

        # 点击高清上传
        click_element(
            self.driver, """ //div[@class="publish-button"] """)
        
        # 多找几次
        for i in range(3):
            try:
                        
                # 点击上传视频
                click_element(
                    self.driver, """ //button[@class="SOCr7n1uoqI-"] """)
                break
            except Exception as e:
                pass
            

    def _get_upload_list(self, folder_path: str, suffixes: list = [".mp4"]) -> List[str]:
        """
            根据文件夹路径获取文件（视频文件）
        """

        path_obj: Path = Path(folder_path)

        if not path_obj.is_dir():
            pass

        video_list = []
        for i in path_obj.iterdir():

            # 不是视频文件（目标文件）
            if i.suffix not in suffixes:
                continue

            video_list.append(i.absolute().__str__())

        return video_list

    @staticmethod
    def select_file(video_path: str):
        """
            mac 系统选择文件
            video_path 完整路径
                video_path = "/Users/dragonfang/....../xxx.mp4"
        """
        os_name = current_os_name()
        
        if os_name == OperatingSystem.MACOS:
            # 激活路径输入
            pyautogui.sleep(2)
            pyautogui.typewrite("/")

            # 输入剩余路径
            pyautogui.sleep(2)
            temp_video_path = video_path[1:]
            # 增加 interval，防止出错
            pyautogui.typewrite(temp_video_path, interval=0.01)

            # 回车，确认路径输入完成
            pyautogui.sleep(2)
            pyautogui.press("enter")

            # 回车，确认选择当前文件
            pyautogui.sleep(2)
            pyautogui.press("enter")
        elif os_name == OperatingSystem.WINDOWS:
            pyautogui.sleep(2)
            pyautogui.typewrite(video_path, interval=0.01)
            pyautogui.sleep(2)
            pyautogui.press("enter")
            pyautogui.sleep(2)
            pyautogui.press("enter")
        
        try:
            # 点击我知道了
            click_element(
                driver, """ //button[@class="ant-btn ant-btn-primary ant-btn-sm IpMQNj-1Gqc-"] """)
        except Exception as e:
            pass

    def set_title(self, title: str):
        """
            设置分类
        """
        # 输入描述
        # "王者荣耀高光时刻 王者 王者荣耀 高光时刻 精彩时刻 #游戏 #王者 #王者荣耀 "
        input_element(
            driver, """ //div[@class="clGhv3UpdEo-"] """, title)
 
    def set_category(self, category_0: str, category_1: str):
        """
            设置分类
        """
        # 输入类型  大类
        click_element(
            driver, """ //div[@class="GuYwDlWOGEM-"]//input[@id="rc_select_0"] """)
        click_element(
            driver, f""" //div[@title="{category_0}"] """)    # "游戏"

        # 输入类型  小类
        click_element(
            driver, """ //div[@class="GuYwDlWOGEM-"]//input[@id="rc_select_2"] """)
        click_element(
            driver, f""" //div[@title="{category_1}"] """)   # "多人在线战术竞技游戏（MOBA）"
    
    def upload(self,up_time:str):
        # 设置定时发布
        click_element(
            driver, """ //span[text()="定时发布"] """)
        input_element(
            driver, """ //div[contains(@class,"ant-picker tOResR7Iq-w-")]//input """, up_time)
        
        pyautogui.sleep(1)
        pyautogui.press("enter")
        pyautogui.sleep(1)
        pyautogui.press("tab")
        pyautogui.sleep(1)

        # 发布
        click_element(
            driver, """ //button[@class="ant-btn ant-btn-primary GncXo-rrppc-"] """)
        
        # 确认发布
        click_element(
            driver, """ //div[@class="ant-modal-body"]//button[@class="ant-btn ant-btn-primary"] """)

        # 删除当前文件
        # os.remove(video_path)
        

kuai_shou_upload = KuaiShouUpload(driver=driver)
